package cn.szzsi._web;

import cn.szzsi._Config;
import cn.szzsi.common.kit.BackUtil;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.IdGen;
import cn.szzsi.common.kit.RegexUtils;
import cn.szzsi.common.model.Member;
import cn.szzsi.core.kit.DesUtil;
import cn.szzsi.core.kit.UtilDate;
import cn.szzsi.service.MemberService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.Cookie;
import java.math.BigDecimal;
import java.util.*;

/**
 * 小程序控制器
 */
public class WeiChatMiniController extends Controller{
    private String wechat_mini_appid= _Config.p.get("wechat_mini_appid");//小程序appid
    private String wechat_mini_secret= _Config.p.get("wechat_mini_secret");//小程序secret

    public void getSessionKeyAndOpenId(){
        System.out.println("**********************************");
        String code=getPara("code");//登录时获取的 code
        String reqUrl="https://api.weixin.qq.com/sns/jscode2session?appid="+wechat_mini_appid+"&secret="+wechat_mini_secret+"&js_code="+code+"&grant_type=authorization_code";
        String result= HttpKit.get(reqUrl);
        JSONObject obj = JSON.parseObject(result);

        String miniOpenid=obj.getString("openid");//小程序openid
        String unionid=obj.getString("unionid");//unionid
        Member memberByUnionid=Member.dao.getByUnionid(unionid);
        System.out.println("miniOpenid----"+miniOpenid+",unionid------"+unionid);
        if(memberByUnionid==null){//unionid不存在,说明既没有注册小程序,也没有注册公众号-->新增
            Member member=new Member();
            member.setId(StrKit.getRandomUUID());
            member.setUnionid(unionid);
            member.setMiniOPenId(miniOpenid);
            member.setCreateDate(new Date());
            member.setRegisterIp(getRequest().getHeader("X-Real-IP"));
            member.save();
        }else{
            if(StrKit.isBlank(memberByUnionid.getMiniOPenId())){//没有注册小程序-->更新
                memberByUnionid.setMiniOPenId(miniOpenid);
                memberByUnionid.update();
            }
        }
        renderJson(BackUtil.success("获取成功",obj));
    }

    public void phoneForLoginForm(){
        String unionid=getPara("unionid");
        setAttr("unionid",unionid);
        render("/template/default/html/binding_phone_login_mini.html");
    }
    public void phoneForRegisterForm(){
        String openid=getPara("openid");
        String unionid=getPara("unionid");
        setAttr("openid",openid);
        setAttr("unionid",unionid);
        render("/template/default/html/binding_phone_register_mini.html");
    }

    @Clear
    public void  phoneapplyForLogin(){
        String unionid=getPara("unionid");
        unionid=new String(Base64.decodeBase64(unionid));
        String phone=getPara("phone");
        String captcha=getPara("phoneCaptcha");
        String password=getPara("password");
        Member member=Member.dao.getByUnionid(unionid);
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码不正确"));
            return;
        }
        if(member==null){
            renderJson(Ret.fail("info","参数错误"));
            return;
        }
        if(StrKit.notBlank(password)){
            member.setPassword(DigestUtils.md5Hex(password));
        }
        member.setPhone(phone);
        member.update();
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());// 写入会员登录Session
        setAttr("loginMember", member);
        renderJson(Ret.ok("info","验证成功!"));


    }

    @Clear
    public void  phoneapplyForRegister(){
        String phone=getPara("phone");
        String captcha=getPara("phoneCaptcha");
        String password=getPara("password");
        String openid=getPara("openid");
        String unionid=getPara("unionid");
        openid=new String(Base64.decodeBase64(openid));
        unionid=new String(Base64.decodeBase64(unionid));
        System.out.println("openid--------------------"+openid);
        /*if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确的手机号"));
            return;
        }*/
        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("","手机验证码已过期,请重新获取"));
            return;
        }
        if(!captcha.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码不正确"));
            return;
        }
        Member member=Member.dao.getByPhone(phone);
        if(member==null){//手机号不存在-->新增
            Member saveMember=new Member();
            saveMember.set("username", phone);
            saveMember.set("password", DigestUtils.md5Hex(password));
            saveMember.set("point", 0);
            saveMember.set("loginFailureCount", 0);
            saveMember.set("registerIp", getRequest().getRemoteAddr());
            saveMember.set("loginIp", getRequest().getRemoteAddr());
            saveMember.set("id", CommonUtil.getUUID());
            saveMember.set("createDate", new Date());
            saveMember.setMiniOPenId(openid);
            saveMember.setUnionid(unionid);
            saveMember.save();
            setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, saveMember.getId());// 写入会员登录Session
        }else{//手机号存在-->更新信息
            setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());// 写入会员登录Session
            member.setMiniOPenId(openid);
            member.setUnionid(unionid);
            member.update();
            setAttr("loginMember", member);
        }
        renderJson(Ret.ok("info","验证成功!"));


    }


    /**
     * 同步微信公众号的粉丝,暂时没用
     */
    public void getFansFromWeixin(){
        Long start=System.currentTimeMillis();
        String result=HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8a609221cd68c2e3&secret=9672bef19ff3524156dbede03af3ffbc");
        org.json.JSONObject jsonObject=new org.json.JSONObject(result);
        String access_token=jsonObject.get("access_token").toString();
        //获取openid数组
        String next_openid="";
        String openidUrl="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid+"";
        String openidResult= HttpKit.get(openidUrl);
        org.json.JSONObject jo=new org.json.JSONObject(openidResult);
        System.out.println("jo------------"+jo);
        Integer total=Integer.valueOf(jo.get("total").toString());//关注该公众账号的总用户数
        Integer count=Integer.valueOf(jo.get("count").toString());//拉取的OPENID个数，最大值为10000
        String openids=jo.getJSONObject("data").get("openid").toString();//["oJTHKwErSUPI376-Qlt3SZyLf7L0", "oJTHKwCgv9v0Gv1P3BZ55WUD3tpM"]
        if(count>0){//拉取的用户数大于0
            openids=openids.substring(1,openids.length()-1).replace("\"","");
            String openidArr[]=openids.split(",");
            List<String> openidList= Arrays.asList(openidArr);
            for( int i=0;i<openidList.size();i++){
                String openid=openidList.get(i);
                String userInfo="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN ";
                String userInfoResult=HttpKit.get(userInfo);
                org.json.JSONObject userInfoObj=new org.json.JSONObject(userInfoResult);
                final String uopenid=userInfoObj.get("openid").toString();
                Member member=Member.dao.getByOpenid(uopenid);
                if(member!=null){
                    String unionid=userInfoObj.getString("unionid");
                    member.setUnionid(unionid);
                    member.update();
                }

            }
            next_openid=jo.get("next_openid").toString();//上一次的最后一个openid
            Integer n=total/count;//调n次接口
            if(total>10000){
                for (int i=0;i<n;n++){
                    openidUrl="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid+"";
                    openidResult=HttpKit.get(openidUrl);
                    jo=new org.json.JSONObject(openidResult);
                    openids=jo.getJSONObject("data").get("openid").toString();//["oJTHKwErSUPI376-Qlt3SZyLf7L0", "oJTHKwCgv9v0Gv1P3BZ55WUD3tpM"]
                    openids=openids.substring(1,openids.length()-1).replace("\"","");
                    openidArr=openids.split(",");
                    openidList=Arrays.asList(openidArr);
                    for( int j=0;j<openidList.size();j++){
                        String openid=openidList.get(i);
                        String userInfo="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN ";
                        String userInfoResult=HttpKit.get(userInfo);
                        org.json.JSONObject userInfoObj=new org.json.JSONObject(userInfoResult);
                        final String uopenid=userInfoObj.get("openid").toString();
                        Member member=Member.dao.getByOpenid(uopenid);
                        if(member!=null){
                            String unionid=userInfoObj.getString("unionid");
                            member.setUnionid(unionid);
                            member.update();
                        }

                    }
                }
            }


        }
        Long end=System.currentTimeMillis();
        System.out.println("时间----------------------"+(end-start)/1000);

        renderJson(Ret.ok("info","操作成功!"));

    }
    public static void main(String[] args) {
        System.out.println(new String(Base64.encodeBase64("测试账号1".getBytes())));
        System.out.println(new String(Base64.decodeBase64("b0RoTUkwWkFLQUJOWXNlb1ZSWmlPWkdheW5xMA==")));
    }

}
